package com.jn.gsondemo.views;



import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jn.gsondemo.R;
import com.jn.gsondemo.adapter.HotSearchAdapter;
import com.jn.gsondemo.entity.HotSearchItem;
import com.jn.gsondemo.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

public class HotSearchActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private HotSearchAdapter adapter;
    private List<HotSearchItem> hotSearchItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_search);

        recyclerView = findViewById(R.id.hot_search_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 解析JSON数据
        String json = JsonUtils.getJsonFromAssets(this, "hotsearch.json");
        hotSearchItems = parseJson(json);

        // 设置适配器
        adapter = new HotSearchAdapter(hotSearchItems);
        recyclerView.setAdapter(adapter);
    }

    private List<HotSearchItem> parseJson(String json) {
        List<HotSearchItem> items = new ArrayList<>();
        JsonArray jsonArray = JsonParser.parseString(json).getAsJsonObject().get("result").getAsJsonArray();
        for (JsonElement element : jsonArray) {
            JsonObject obj = element.getAsJsonObject();
            HotSearchItem item = new HotSearchItem();
            item.setTitle(obj.get("title").getAsString());
            item.setHotValue(obj.get("hotValue").getAsString());
            item.setLink(obj.get("link").getAsString());
            items.add(item);
        }
        return items;
    }
}